package org.example.common.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Configuration
public class SaTokenConfigure {

    // 允许任意主机
    private static final List<String> ALLOWED_ORIGINS = Arrays.asList("*");

    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico")
                .addExclude("/ws/**")
                .addExclude("/api/excel/**")
                .setAuth(obj -> {
                    SaRouter.match("/**")
                            .notMatch("/api/auth/login","/api/user/phone/code","/api/auth/smsLogin", "/ws/**")
                            .check( StpUtil::checkLogin);
                })

                .setError(e -> {
                    return SaResult.error(e.getMessage());
                })

                .setBeforeAuth(r -> {
                    String origin = SaHolder.getRequest().getHeader("Origin");

                    SaHolder.getResponse()
                            .setServer("sa-server")
                            .setHeader("X-Frame-Options", "SAMEORIGIN")
                            .setHeader("X-XSS-Protection", "1; mode=block")
                            .setHeader("X-Content-Type-Options", "nosniff")
                            .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT")
                            .setHeader("Access-Control-Max-Age", "3600")
                            .setHeader("Access-Control-Allow-Headers", "content-type, satoken, authorization, *");

                    // 允许任意来源
                    if (origin != null) {
                        SaHolder.getResponse()
                                .setHeader("Access-Control-Allow-Origin", origin)
                                .setHeader("Access-Control-Allow-Credentials", "true");
                    } else {
                        // 当没有Origin头时（如直接请求），设置允许任意
                        SaHolder.getResponse()
                                .setHeader("Access-Control-Allow-Origin", "*");
                    }
                });
    }
}